﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

namespace OpenPasteSpider.EntityFrameworkCore
{

    /// <summary>
    /// 
    /// </summary>
    public class OpenPasteSpiderDbContextFactory : IDesignTimeDbContextFactory<OpenPasteSpiderDbContext>
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        /// <returns></returns>
        public OpenPasteSpiderDbContext CreateDbContext(string[] args)
        {
            //Console.WriteLine("PgsqlDbContextFactory.CreateDbContext");

            //啥时候执行的，执行了多少次?
            AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
            var configuration = BuildConfiguration();

            var builder = new DbContextOptionsBuilder<OpenPasteSpiderDbContext>()
                .UseNpgsql(configuration.GetConnectionString("MainConnectionString"));
            //    .ReplaceService<IMigrationsSqlGenerator, MyMigrationsSqlGenerator>();

            return new OpenPasteSpiderDbContext(builder.Options);
        }

        private static IConfigurationRoot BuildConfiguration()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false)
                .AddJsonFile($"appsettings.Development.json", optional: true)
                .AddEnvironmentVariables();

            return builder.Build();
        }
    }
}
